<?php

namespace App\Http\Wechat\Controller;

use App\Service\Wechat\MpService;
use App\Http\Common\Result;
use Common\CommonController;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\PostMapping;
use Psr\Http\Message\ResponseInterface;

#[Controller('api/wechat/mp')]
class MpController extends CommonController
{
    #[Inject]
    public Mpservice $service;

    #[GetMapping('getRedirectUrl')]
    public function getRedirectUrl(): Result
    {
        return $this->success($this->service->getRedirectUrl(
            $this->valid(
                ['to_url' => 'required|string', 'scope' => 'string'],
                []
            )
        ));
    }

    #[GetMapping('redirectTo')]
    public function redirect(): ResponseInterface
    {
        $data = $this->valid();
        $url = $data['r'];
        unset($data['r']);
        if ($data) {
            if (str_contains($url, '?')) $url .= '&';
            else $url .= '?';
            $url .= http_build_query($data);
        }
        return $this->redirectTo($url);
    }

    #[PostMapping('login')]
    public function login(): Result
    {
        return $this->success($this->service->login($this->valid(['code' => 'string'])));
    }
}
